package com.sbj.socket;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2024/8/31 14:25
 */
@Component
@ServerEndpoint("/timeSocket/{memberId}")
@Slf4j
@SaIgnore
public class TimeSocketServer {

    private final static Map<Integer, Session> CLIENTS = MapUtil.newConcurrentHashMap();


    @OnOpen
    public void onOpen(Session session,@PathParam("memberId") Integer memberId) throws IOException {
        CLIENTS.put(memberId, session);
        log.info("onOpen:{}",session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
       log.info("message:{}" ,message);
    }

    @OnClose
    public void onClose(@PathParam("memberId") Integer memberId) throws IOException {
        CLIENTS.remove(memberId);
    }

    public void sendMessage(String message,Integer memberId) throws IOException {
        CLIENTS.get(memberId).getBasicRemote().sendText(message);
    }

}
